﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CMSMVC4.Areas.Admin.Models;
using CMSMVC4.Filters;

namespace CMSMVC4.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin,Equipment")]
    public class ThietBiController : Controller
    {
        //
        // GET: /Admin/ThietBi/
        CMSMVC4Entities db = new CMSMVC4Entities();
        CommandSql cm = new CommandSql();

        public ActionResult Index()
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/ThietBi").Rows[0]["Parrent"];
            string curte = cm.GetLanguage();
            var data = db.CateLangs.OrderByDescending(x=>x.Category.Sort).Where(x => x.Category.Type == MenuType.ThiteBi && x.LanguageCode.Equals(curte) && x.Category.Status == CategoriStatus.Thuong).ToList();
            return View(data);
        }

        public ActionResult DanhMuc()
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/ThietBi/DanhMuc").Rows[0]["Parrent"];
            string curte = cm.GetLanguage();
            var data = db.CateLangs.OrderByDescending(x => x.Category.Sort).Where(x => x.Category.Type == MenuType.ThiteBi && x.LanguageCode.Equals(curte) && x.Category.Status == CategoriStatus.Foder).ToList();
            return View(data);
        }

        public ActionResult Sort(int id)
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/ThietBi/Sort/0").Rows[0]["Parrent"];
            string curte = cm.GetLanguage();
            var data = db.CateLangs.OrderByDescending(x => x.Category.Sort).Where(x => x.Category.Type == MenuType.ThiteBi && x.LanguageCode.Equals(curte) && x.Category.Status == CategoriStatus.Thuong && x.Category.paren == id).ToList();
            ViewBag.id = id;
            return View(data);
        }

        public ActionResult SortFolder()
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/ThietBi").Rows[0]["Parrent"];
            string curte = cm.GetLanguage();
            var data = db.CateLangs.OrderByDescending(x => x.Category.Sort).Where(x => x.Category.Type == MenuType.ThiteBi && x.LanguageCode.Equals(curte) && x.Category.Status == CategoriStatus.Foder).ToList();
            return View(data);
        }

        [HttpPost]
        public JsonResult Sort(ob[] aro)
        {
            if (aro != null)
            {
                for (int i = 0; i < aro.Length; i++)
                {
                    int id = Convert.ToInt32(aro[i].id);
                    Category ct = db.Categories.FirstOrDefault(x => x.Id == id);
                    if (ct != null)
                    {
                        int sort = Convert.ToInt32(aro[i].sort);
                        ct.Sort = sort;
                        db.SaveChanges();
                    }
                }
                return Json("Lưu dữ liệu thành công", JsonRequestBehavior.AllowGet);
            }
            return Json("Lỗi hệ thống không lưu được dữ liệu", JsonRequestBehavior.AllowGet);
        }

        #region xoa
        [HttpGet]
        public ActionResult Xoa(string id)
        {
            return PartialView();
        }

        [HttpPost]
        public ActionResult Xoa(string[] id)
        {
            if (id != null)
            {
                foreach (var i in id)
                {
                    int idcomment;
                    int.TryParse(i, out idcomment);
                    var row = db.Categories.FirstOrDefault(x => x.Id == idcomment);
                    db.Categories.DeleteObject(row);
                    db.SaveChanges();
                }
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult XoaDanhMuc(string[] id)
        {
            if (id != null)
            {
                foreach (var i in id)
                {
                    int idcomment;
                    int.TryParse(i, out idcomment);
                    var row = db.Categories.FirstOrDefault(x => x.Id == idcomment);
                    if (row != null)
                    {
                        var cate = db.Categories.Where(x => x.paren == row.Id);
                        foreach (var item in cate)
                        {
                            var chiren = db.Categories.FirstOrDefault(x => x.Id == item.Id);
                            if (chiren != null)
                            {
                                db.Categories.DeleteObject(chiren);
                            }
                        }
                        db.Categories.DeleteObject(row);
                        db.SaveChanges();
                    }
                }
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
        #endregion
        public ActionResult XoaTab(string id)
        {
            int idpage;
            int.TryParse(id, out idpage);
            var row = db.Pages.FirstOrDefault(x => x.Id == idpage);
            if (row != null)
            {
                db.Pages.DeleteObject(row);
                db.SaveChanges();
            }
            if (Request.IsAjaxRequest())
            {
                var datav = db.PageLangs.Where(x => x.Page.CategoriesID == row.CategoriesID && x.LanguageCode.Equals("vi-vn")).OrderBy(x => x.Page.Tab).ToList();
                var datae = db.PageLangs.Where(x => x.Page.CategoriesID == row.CategoriesID && x.LanguageCode.Equals("en-us")).OrderBy(x => x.Page.Tab).ToList();
                ViewBag.datav = datav;
                ViewBag.datae = datae;
                return PartialView("ListTabAjax");
            }
            return RedirectToAction("Them", new { id = row.CategoriesID });
        }

        public ActionResult Them(string id,string mess)
        {
            ViewBag.mess = mess;
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/ThietBi/Them").Rows[0]["Parrent"];
            int idcate;
            Category ctf;
            if (int.TryParse(id, out idcate))
            {
                ctf = db.Categories.FirstOrDefault(x => x.Id == idcate);
                if (ctf == null)
                {
                    return View("Error");
                }
            }
            else
            {
                ctf = db.Categories.FirstOrDefault(x => x.Status == CategoriStatus.Nhap && x.Type == MenuType.ThiteBi);
                if (ctf == null)
                {
                    int sort = 0;
                    var data = db.Categories.OrderByDescending(x=>x.Sort).FirstOrDefault(x => x.Type == MenuType.ThiteBi && x.Status == CategoriStatus.Thuong && x.paren == 0);
                    if (data != null)
                    {
                        sort = (int)data.Sort +1;
                    }
                    Category ct = new Category();
                    ct.Type = MenuType.ThiteBi;
                    ct.Status = CategoriStatus.Nhap;
                    ct.Sort = sort;
                    db.Categories.AddObject(ct);
                    db.SaveChanges();
                    ctf = db.Categories.FirstOrDefault(x => x.Status == CategoriStatus.Nhap && x.Type == MenuType.ThiteBi);
                }
            }
            var ctlv = db.CateLangs.FirstOrDefault(x => x.CategoriesId == ctf.Id && x.LanguageCode.Equals("vi-vn"));
            var ctle = db.CateLangs.FirstOrDefault(x => x.CategoriesId == ctf.Id && x.LanguageCode.Equals("en-us"));
            if (ctlv == null)
            {
                CateLang ctl = new CateLang();
                ctl.CategoriesId = ctf.Id;
                ctl.Name = "Default - Vi";
                ctl.LanguageCode = "vi-vn";
                db.CateLangs.AddObject(ctl);
                db.SaveChanges();
            }
            if (ctle == null)
            {
                CateLang ctl = new CateLang();
                ctl.CategoriesId = ctf.Id;
                ctl.Name = "Default - En";
                ctl.LanguageCode = "en-us";
                db.CateLangs.AddObject(ctl);
                db.SaveChanges();
            }
            var page = db.Pages.FirstOrDefault(x => x.CategoriesID == ctf.Id);
            if (page == null)
            {
                Page p = new Page();
                p.CategoriesID = ctf.Id;
                p.Tab = 1;
                p.View = 0;
                p.Status = PageStatus.Thuong;
                p.Date = DateTime.Now;
                db.Pages.AddObject(p);
                db.SaveChanges();
                page = db.Pages.FirstOrDefault(x => x.CategoriesID == ctf.Id);
            }
            PageLang pglv = db.PageLangs.FirstOrDefault(x => x.PageId == page.Id && x.LanguageCode.Equals("vi-vn"));
            PageLang pgle = db.PageLangs.FirstOrDefault(x => x.PageId == page.Id && x.LanguageCode.Equals("en-us"));
            if (pglv == null)
            {
                PageLang pl = new PageLang();
                pl.LanguageCode = "vi-vn";
                pl.PageId = page.Id;
                pl.Name = "Tab 1";
                db.PageLangs.AddObject(pl);
                db.SaveChanges();
            }
            if (pgle == null)
            {
                PageLang pl = new PageLang();
                pl.LanguageCode = "en-us";
                pl.PageId = page.Id;
                pl.Name = "Tab 1";
                db.PageLangs.AddObject(pl);
                db.SaveChanges();
            }
            return View(ctf);
        }

        [HttpPost]
        public ActionResult them(AddThietBiModel model)
        {
            string mess;
            if (ModelState.IsValid)
            {
                var cate = db.Categories.FirstOrDefault(x => x.Id == model.idcate);
                if (cate != null)
                {
                    cate.Status = CategoriStatus.Thuong;
                    cate.paren = model.paren;
                    int sort = 0;
                    var data = db.Categories.OrderByDescending(x => x.Sort).FirstOrDefault(x => x.Type == MenuType.ThiteBi && x.Status == CategoriStatus.Thuong && x.paren == model.paren);
                    if (data != null)
                    {
                        sort = (int)data.Sort + 1;
                    }
                    cate.Sort = sort;
                    var catev = db.CateLangs.FirstOrDefault(x => x.CategoriesId == model.idcate && x.LanguageCode.Equals("vi-vn"));
                    var catee = db.CateLangs.FirstOrDefault(x => x.CategoriesId == model.idcate && x.LanguageCode.Equals("en-us"));
                    if (catev != null) catev.Name = model.namecatev;
                    if (catee != null) catee.Name = model.namecatee;
                    foreach (var i in model.tab)
                    {
                        var plv = db.PageLangs.FirstOrDefault(x => x.PageId == i.idpage && x.LanguageCode.Equals("vi-vn"));
                        var ple = db.PageLangs.FirstOrDefault(x => x.PageId == i.idpage && x.LanguageCode.Equals("en-us"));
                        if (plv != null)
                        {
                            plv.Name = i.namepagev;
                            plv.FullContent = i.fullv;
                            plv.Summary = i.sumv;
                        }
                        if (ple != null)
                        {
                            ple.Name = i.namepagee;
                            ple.FullContent = i.fulle;
                            ple.Summary = i.sume;
                        }
                    }
                    db.SaveChanges();
                }
                if (Request.IsAjaxRequest())
                {
                    return Json("Lưu dữ liệu thành công", JsonRequestBehavior.AllowGet);
                }
                string mes = "Lưu dữ liệu thành công";
                return RedirectToAction("Them", new { id = model.idcate , mess = mes});
            }
            if (Request.IsAjaxRequest())
            {
                return Json("Không Lưu Được Dữ Liệu", JsonRequestBehavior.AllowGet);
            }
            return View("Error");
        }

        public ActionResult NewTab(string id)
        {
            int idcate;
            int.TryParse(id, out idcate);
            var cate = db.Categories.FirstOrDefault(x => x.Id == idcate);
            if (cate != null)
            {
                int? tab = 1;
                var page = db.Pages.OrderByDescending(x => x.Tab).FirstOrDefault(x => x.CategoriesID == cate.Id);
                if (page != null)
                {
                    tab = page.Tab + 1;
                }
                Page pg = new Page();
                pg.CategoriesID = idcate;
                pg.Tab = tab;
                pg.Status = PageStatus.Thuong;
                pg.View = 0;
                db.Pages.AddObject(pg);
                db.SaveChanges();
                var page2 = db.Pages.OrderByDescending(x => x.Tab).FirstOrDefault(x => x.CategoriesID == cate.Id);
                if (page2 != null)
                {
                    PageLang pgl = new PageLang();
                    pgl.LanguageCode = "vi-vn";
                    pgl.PageId = page2.Id;
                    pgl.Name = "Tab " + page2.Tab.ToString();
                    db.PageLangs.AddObject(pgl);
                    pgl = new PageLang();
                    pgl.LanguageCode = "en-us";
                    pgl.PageId = page2.Id;
                    pgl.Name = "Tab " + page2.Tab.ToString();
                    db.PageLangs.AddObject(pgl);
                    db.SaveChanges();
                    if (Request.IsAjaxRequest())
                    {
                        var datav = db.PageLangs.Where(x => x.Page.CategoriesID == idcate && x.LanguageCode.Equals("vi-vn")).OrderBy(x => x.Page.Tab).ToList();
                        var datae = db.PageLangs.Where(x => x.Page.CategoriesID == idcate && x.LanguageCode.Equals("en-us")).OrderBy(x => x.Page.Tab).ToList();
                        ViewBag.datav = datav;
                        ViewBag.datae = datae;
                        return PartialView("ListTabAjax");
                    }
                    return RedirectToAction("Them", new { id });
                }
            }
            return View("Error");
        }

        [ChildActionOnly]
        public ActionResult listTab(int id)
        {
            var datav = db.PageLangs.Where(x => x.Page.CategoriesID == id && x.LanguageCode.Equals("vi-vn")).OrderBy(x => x.Page.Tab).ToList();
            var datae = db.PageLangs.Where(x => x.Page.CategoriesID == id && x.LanguageCode.Equals("en-us")).OrderBy(x => x.Page.Tab).ToList();
            ViewBag.datav = datav;
            ViewBag.datae = datae;
            return PartialView();
        }

        [ChildActionOnly]
        public ActionResult GetNameCate(int id)
        {
            var datav = db.CateLangs.FirstOrDefault(x => x.CategoriesId == id && x.LanguageCode.Equals("vi-vn"));
            var datae = db.CateLangs.FirstOrDefault(x => x.CategoriesId == id && x.LanguageCode.Equals("en-us"));
            ViewBag.datav = datav;
            ViewBag.datae = datae;
            return PartialView();
        }

        [ChildActionOnly]
        public ActionResult SetHome(int id)
        {
            var page = db.Pages.FirstOrDefault(x => x.CategoriesID == id && x.Status == PageStatus.GioiThieu);
            if (page == null)
            {
                page = db.Pages.Where(x => x.CategoriesID == id).OrderBy(x => x.Tab).FirstOrDefault();
                if (page != null)
                {
                    ViewBag.pageid = page.Id;
                }
            }
            return PartialView();
        }

        [ChildActionOnly]
        public ActionResult GetNameFoder(int id)
        {
            var cate = db.Categories.FirstOrDefault(x => x.Id == id);
            if (cate != null)
            {
                string lag = cm.GetLanguage();
                var foder = db.CateLangs.FirstOrDefault(x => x.Category.Id == cate.paren && x.LanguageCode.Equals(lag));
                if (foder != null)
                {
                    ViewBag.foder = foder.Name;
                }
            }
            return PartialView();
        }

        public ActionResult ThemDanhMuc()
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/ThietBi").Rows[0]["Parrent"];
            return View();
        }

        [HttpPost]
        public ActionResult ThemDanhMuc(ThemDanhMucModel model)
        {
            if (ModelState.IsValid)
            {
                int sort = 0;
                var cate =
                    db.Categories.OrderByDescending(x => x.Sort).FirstOrDefault(x => x.Status == CategoriStatus.Foder && x.Type == MenuType.ThiteBi);
                if (cate != null)
                {
                    var i = cate.Sort + 1;
                    if (i != null) sort = (int) i;
                }
                Category row = new Category();
                row.Sort = sort;
                row.Status = CategoriStatus.Foder;
                row.Type = MenuType.ThiteBi;
                row.paren = 0;
                db.Categories.AddObject(row);
                db.SaveChanges();
                cate =
                    db.Categories.OrderByDescending(x => x.Sort).FirstOrDefault(x => x.Status == CategoriStatus.Foder && x.Type == MenuType.ThiteBi);
                if (cate != null)
                {
                    CateLang clv = new CateLang();
                    clv.CategoriesId = cate.Id;
                    clv.LanguageCode = "vi-vn";
                    clv.Name = model.namecatev;
                    db.CateLangs.AddObject(clv);
                    CateLang cle = new CateLang();
                    cle.CategoriesId = cate.Id;
                    cle.LanguageCode = "en-us";
                    cle.Name = model.namecatev;
                    db.CateLangs.AddObject(cle);
                    db.SaveChanges();
                    return RedirectToAction("DanhMuc");
                }
            }
            return View();
        }

        public ActionResult SuaDanhMuc(int id)
        {
            var clv = db.CateLangs.FirstOrDefault(x => x.CategoriesId == id && x.LanguageCode.Equals("vi-vn"));
            var cle = db.CateLangs.FirstOrDefault(x => x.CategoriesId == id && x.LanguageCode.Equals("en-us"));
            SuaDanhMucModel model = new SuaDanhMucModel();
            if (clv !=null)
            {
                model.idv = clv.Id;
                model.namecatev = clv.Name;
            }
            if (cle != null)
            {
                model.ide = cle.Id;
                model.namecatee = cle.Name;
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult SuaDanhMuc(SuaDanhMucModel model)
        {
            if (ModelState.IsValid)
            {
                var clv = db.CateLangs.FirstOrDefault(x => x.Id == model.idv);
                if (clv != null)
                {
                    clv.Name = model.namecatev;
                    db.SaveChanges();
                }
                var cle = db.CateLangs.FirstOrDefault(x => x.Id == model.ide);
                if (cle != null)
                {
                    cle.Name = model.namecatee;
                    db.SaveChanges();
                }
                ModelState.AddModelError("","Thay Đổi Dữ Liệu Thành Công");
            }
            return View(model);
        }

        [ChildActionOnly]
        public ActionResult DanhSachDanhMuc(int id)
        {
            string lag = cm.GetLanguage();
            var data = db.CateLangs.OrderByDescending(x => x.Category.Sort).Where(x => x.LanguageCode.Equals(lag) && x.Category.Status == CategoriStatus.Foder && x.Category.Type == MenuType.ThiteBi).ToList();
            List<ItemData> lst = new List<ItemData>();
            foreach (var item in data)
            {
                ItemData ida = new ItemData();
                ida.name = item.Name;
                ida.value = item.CategoriesId;
                lst.Add(ida);
            }
            ItemData itemnew = new ItemData();
            itemnew.name = "Không Dùng Danh Mục";
            itemnew.value = 0;
            lst.Insert(0,itemnew);
            SelectList list = new SelectList(lst, "value", "name");
            DanhSachDanhMucModel model = new DanhSachDanhMucModel();
            model.data = list;
            model.paren = id;
            return PartialView(model);
        }
    }
}
